package com.wnhz.work.yz.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.UserBean;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SkillBookPop;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * -----上传身份证
 */
public class UploadCardActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "UploadCardActivity";

    private TextView prompt_tv;
    private ImageView add1, add2, delete1, delete2;

    private String imagePath1, imagePath2;
    private int currentClick = 0;

    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    private String imageName;// 原图名称
    private String imagePath;// 原图路径
    private File tempFile;

    private static final String FilesPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/youZhu/Compress/"; // 图片及其他数据保存文件夹
    private static File compressFile = new File(FilesPath);
    private static final String PhotePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/youZhu/"; // 图片及其他数据保存文件夹
    private static File PhoteFilePath = new File(PhotePath);
    private static final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");


    private String realname;
    private String card_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_card);

        initView();
        initData();
        initTitle();
    }


    public void initData() {
        String prompt = "1、照片中的信息必须真实有效且清晰可见" + "\n" + "2、手持身份证的人五官清晰" + "\n" + "3、身份证上面的所有信息真实" + "\n" + "4、以上案例图片隐藏了信息";
        prompt_tv.setText(prompt);
        realname = getIntent().getStringExtra("realname");
        card_id = getIntent().getStringExtra("card_id");

    }

    private TextView title;

    private void initTitle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("身份证上传");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView tv_right = (TextView) findViewById(R.id.view_main_right_text);
        tv_right.setText("提交");
        tv_right.setTextColor(Color.parseColor("#008c99"));
        tv_right.setVisibility(View.VISIBLE);
        findViewById(R.id.btn_main_right).setVisibility(View.VISIBLE);
        findViewById(R.id.btn_main_right).setOnClickListener(this);
    }


    public void initView() {

        prompt_tv = (TextView) findViewById(R.id.prompt_tv);

        add1 = (ImageView) findViewById(R.id.add_img);
        add2 = (ImageView) findViewById(R.id.add_img2);

        delete1 = (ImageView) findViewById(R.id.ic_card_delete1);
        delete2 = (ImageView) findViewById(R.id.ic_card_delete2);

        add1.setOnClickListener(this);
        add2.setOnClickListener(this);

        delete1.setOnClickListener(this);
        delete2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            //保存
            case R.id.btn_main_right:
                if (null != imagePath1 && null != imagePath2) {
                    //网络请求的方法
                    upload();
                } else {
                    MyToast("请上传完整的证件照");

                }
                break;
            case R.id.btn_main_left:
                finish();
                break;

            //身份证正面照
            case R.id.add_img:
                if (null == imagePath1) {
                    currentClick = 1;
                    showPopmenu(v);
                } else {
//                    intent = new Intent(UploadCardActivity.this, ZoomImage.class);
//                    intent.putExtra("path", imagePath1);
//                    startActivity(intent);
                }
                break;

            //身份证背面照
            case R.id.add_img2:
                if (null == imagePath2) {
                    currentClick = 2;
                    showPopmenu(v);
                } else {
//                    intent = new Intent(UploadCardActivity.this, ZoomImage.class);
//                    intent.putExtra("path", imagePath2);
//                    startActivity(intent);
                }
                break;

            //删除正面照
            case R.id.ic_card_delete1:
                imagePath1 = null;
                delete1.setVisibility(View.GONE);
                add1.setImageResource(R.mipmap.ic_tianjiashenfenzhengzhao);
                break;

            //删除背面照
            case R.id.ic_card_delete2:
                imagePath2 = null;
                delete2.setVisibility(View.GONE);
                add2.setImageResource(R.mipmap.ic_tianjiashenfenzhengzhao);
                break;

        }
    }

    private void upload() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("realname", realname);
        map.put("cardId", card_id);
        String targetPath = imagePath1;
        //调用压缩图片的方法，返回压缩后的图片path
        String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
        File compressedPic = new File(compressImage);
//
        String targetPath2 = imagePath2;
        //调用压缩图片的方法，返回压缩后的图片path
        String compressImage2 = BitnapUtils.compressImage(targetPath2, targetPath2, 30);
        File compressedPic2 = new File(compressImage);


        map.put("idcard_pic1", compressedPic);
        map.put("idcard_pic2", compressedPic2);
        Log.i(TAG, "upload: = " + imagePath1);
        Log.i(TAG, "upload: = " + imagePath2);
        Log.i(TAG, "upload: = " + realname);
        Log.i(TAG, "upload: = " + card_id);
        XUtil.Post(Url.MEMBER_UPLOADIDENTIFY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: realname= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(UploadCardActivity.this, LoginNewActivity.class));
//                        return;
//                    }
                    if ("1".equals(res)) {
                        MyToast(info);
                        UserBean bean = new UserBean();
                        bean.setUserName(realname);
                        Intent intent = new Intent(UploadCardActivity.this, UserInfoManagerActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        MyToast(info);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });

    }


    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }


    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    System.out.println("=====1234=====");
                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/WorksComing/", imageName)));
                    }
                    System.out.println("拍照的路径---" + imageName);
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

//                    intent = new Intent(Intent.ACTION_GET_CONTENT);
//                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();

                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    String imagePath = AlbumImagePath.getPath(this, uri);
                    System.out.println("imagePath**====www==" + imagePath);

                    if (!compressFile.exists()) {
                        compressFile = new File(FilesPath);
                        compressFile.mkdirs();
                    }
//                    String targetPath = compressFile.getAbsolutePath() +df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//                    updateImage(compressImage, uri, currentClick);
                    updateImage(imagePath, uri, currentClick);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {

                    tempFile = new File(Environment.getExternalStorageDirectory() + "/WorksComing/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

                    if (!compressFile.exists()) {
                        compressFile = new File(FilesPath);
                        compressFile.mkdirs();
                    }
                    File file = new File(imagePath);
//                    Log.i(TAG, "onActivityResult: 拍照图片是否存在===" + file.exists());

                    if (!file.exists()) {
                        return;
                    }

//                    String targetPath = compressFile.getAbsolutePath() + df.format(new Date()) + ".jpg";
//                    //调用压缩图片的方法，返回压缩后的图片path
//                    final String compressImage = CompressImageUtils.compressImage(imagePath, targetPath, 60);
//                    Log.i(TAG, "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
//
//                    updateImage(compressImage, uri, currentClick);
                    updateImage(imagePath, uri, currentClick);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;

            default:
                break;
        }

    }

    private void updateImage(String imagePath, Uri uri, int currentClick) {
        if (null == imagePath) {
            return;
        }

        System.out.println("===修改的imagePath===" + imagePath);

        switch (currentClick) {
            case 1:
                imagePath1 = imagePath;
                ImageLoader.getInstance().displayImage("file://" + imagePath1, add1);
                delete1.setVisibility(View.VISIBLE);

                break;

            case 2:
                imagePath2 = imagePath;
                ImageLoader.getInstance().displayImage("file://" + imagePath2, add2);
                delete2.setVisibility(View.VISIBLE);

                break;

            default:
                break;
        }


    }
}
